package com.engine.generalledger.cronjob;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.Year;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公共科目核算关系执行数定时任务
 */
public class SujectAccountCronJob extends BaseCronJob {

    private Logger logger = getLogger();

    private String url =  Prop.getPropValue("businessbudgetpz", "url");

    @Override
    public void execute() {
        String nowTime = TimeUtil.getCurrentTimeString();
        int nowYear = Year.now().getValue();
        int num = 1;

        logger.setClassname(this.getClass().getCanonicalName());
        logger.info("公共科目核算关系执行数定时任务...start,执行时间：" + nowTime);


        try {
            RecordSet rs = new RecordSet();

            //封装入参
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("year", nowYear + "");
            jsonObject.put("begindate", "ALL");
            jsonObject.put("enddate", "ALL");
            jsonObject.put("pageIndex", num);
            jsonObject.put("pageSize", 100);

            //请求接口
            String ret = sendJson(url, jsonObject.toString());
            logger.info("公共科目核算关系接口调用结果Url："+url+",param:"+jsonObject.toString()+",result:"+ret+",执行时间：" + nowTime);

            //解析出参
            JSONObject json = JSONObject.fromObject(ret);
            JSONObject responseBosy = json.getJSONObject("responseBosy");
            String code = responseBosy.getString("code");
            logger.info("公共科目核算关系...code"+code);
            if (!code.equals("S")) {
                return;
            }
            JSONArray jsonArray = responseBosy.getJSONArray("data");

            //删除数据
            String deleteSql = "DELETE FROM uf_kmfzhs WHERE `year` = ? ";
            boolean deleteFlag = rs.executeUpdate(deleteSql, nowYear);
            logger.info("公共科目核算关系删除delte,sql:"+deleteSql+",year:"+nowYear+",flag=" + deleteFlag);

            add(jsonArray);

            while (jsonArray.size() >= 100) {

                jsonObject.put("pageIndex",++num);
                //请求接口
                ret = sendJson(url, jsonObject.toString());
                logger.info("公共科目核算关系接口调用结果Url："+url+",param:"+jsonObject.toString()+",result:"+ret+",执行时间：" + nowTime);
                json = JSONObject.fromObject(ret);
                responseBosy = json.getJSONObject("responseBosy");
                jsonArray = responseBosy.getJSONArray("data");

                //重新添加
                add(jsonArray);
            }
        } catch (Exception e) {
            logger.error("公共科目核算关系定时任务...异常err," + e.getMessage() + ",执行时间：" + nowTime, e);
        }
        logger.info("公共科目核算关系执行数定时任务...end,执行时间：" + nowTime);
    }


    private void add(List<JSONObject> list) {
        //增加数据
        RecordSet recordSet = new RecordSet();
        String sql = "INSERT INTO uf_kmfzhs( hsid,ChartOfAccount,Ledger,AccountTitleCode,IsDept,IsPerson,IsCAndS,IsCrcy,Crcy,IsQty,QtyEx01,QtyEx02,QtyEx03,IsIT,IsITNotNull,CAndSRange,BizCtrl,AccBookStyle,EndPeriodBal,IsTransferBal,IsSameAsBalDir,IsDeficitCtrl,IsCAndSBizNum,SrcFIDoc,IsCC,IsUserDefnItem01,IsUserDefnItem02,IsUserDefnItem03,IsUserDefnItem04,IsUserDefnItem05,IsUserDefnItem06,IsUserDefnItem07,IsRefBiz01,IsRefBiz02,IsRefBiz03,IsRefBiz04,year,timestamp_createdby,timestamp_createdon,timestamp_lastchangedby,timestamp_lastchangedon )  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        List<List> datalist = new ArrayList<>();
        int index = 0;
        for (Map map : list) {
            List<Object> data = new ArrayList<>();
            data.add(Util.null2String(map.get("iD")));
            data.add(Util.null2String(map.get("chartOfAccount")));
            data.add(Util.null2String(map.get("ledger")));
            data.add(Util.null2String(map.get("accountTitleCode")));
            data.add(Util.null2String(map.get("isDept")));
            data.add(Util.null2String(map.get("isPerson")));
            data.add(Util.null2String(map.get("isCAndS")));
            data.add(Util.null2String(map.get("isCrcy")));
            data.add(Util.null2String(map.get("Crcy")));
            data.add(Util.null2String(map.get("isQty")));
            data.add(Util.null2String(map.get("qtyEx01")));
            data.add(Util.null2String(map.get("qtyEx02")));
            data.add(Util.null2String(map.get("qtyEx03")));
            data.add(Util.null2String(map.get("isIT")));
            data.add(Util.null2String(map.get("isITNotNull")));
            data.add(Util.null2String(map.get("cAndSRange")));
            data.add(Util.null2String(map.get("bizCtrl")));
            data.add(Util.null2String(map.get("accBookStyle")));
            data.add(Util.null2String(map.get("endPeriodBal")));
            data.add(Util.null2String(map.get("isTransferBal")));
            data.add(Util.null2String(map.get("isSameAsBalDir")));
            data.add(Util.null2String(map.get("isDeficitCtrl")));
            data.add(Util.null2String(map.get("isCAndSBizNum")));
            data.add(Util.null2String(map.get("srcFIDoc")));
            data.add(Util.null2String(map.get("isCC")));
            data.add(Util.null2String(map.get("isUserDefnItem01")));
            data.add(Util.null2String(map.get("isUserDefnItem02")));
            data.add(Util.null2String(map.get("isUserDefnItem03")));
            data.add(Util.null2String(map.get("isUserDefnItem04")));
            data.add(Util.null2String(map.get("isUserDefnItem05")));
            data.add(Util.null2String(map.get("isUserDefnItem06")));
            data.add(Util.null2String(map.get("isUserDefnItem07")));
            data.add(Util.null2String(map.get("isRefBiz01")));
            data.add(Util.null2String(map.get("isRefBiz02")));
            data.add(Util.null2String(map.get("isRefBiz03")));
            data.add(Util.null2String(map.get("isRefBiz04")));
            data.add(Util.null2String(map.get("year")));
            data.add(Util.null2String(map.get("timestamp_createdby")));
            data.add(Util.null2String(map.get("timestamp_createdon")));
            data.add(Util.null2String(map.get("timestamp_lastchangedby")));
            data.add(Util.null2String(map.get("timestamp_lastchangedon")));
            datalist.add(data);
            logger.info("公共科目核算关系定时任务新增比较....data=" + data+"params+"+map+".....执行次数:"+(++index));
        }
        boolean b = recordSet.executeBatchSql(sql, datalist);
        logger.info("公共科目核算关系定时任务新增...flag=" + b);
    }

    /**
     * 发送post请求
     *
     * @param targetUrl
     * @param jsonParams
     * @return
     */
    private String sendJson(String targetUrl, String jsonParams) {
        JSONObject res = new JSONObject();
        res.put("err", "");
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(targetUrl);
            StringEntity entity = new StringEntity(jsonParams);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer  " + Prop.getPropValue("businessbudgetpz", "bearer"));
            httpPost.setHeader("X-ECC-Current-Tenant", "10000");
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            res.put("statusCode", statusCode);
            String responseBody = EntityUtils.toString(response.getEntity());
            res.put("responseBosy", responseBody);
            httpClient.close();

            return res.toString();

        } catch (Exception e) {
            res.put("err", e.getMessage());
            logger.error("公共科目核算关系定时任务调用失败...message:" + e.getMessage(), e);
            return res.toString();
        }
    }



}
